package com.cy.wenxinapi.util;


import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class UnzipUtility {


    public static void main(String[] args) throws IOException, ArchiveException {

        String zipFilePath = "C:\\Users\\morning\\Desktop\\TC20230901000012(1).zip";
        String destinationFolderPath =  "C:\\Users\\morning\\Desktop\\TC20230901000012";
        String password = "123123";

        UnzipUtility unzipUtility = new UnzipUtility();
        unzipUtility.unzip(zipFilePath, destinationFolderPath, password);
        System.out.println("解压缩完成.");

    }

    public void unzip(String zipFilePath, String destinationFolderPath, String password) throws ArchiveException, IOException {
        byte[] buffer = new byte[4096];

        try (FileInputStream fileInputStream = new FileInputStream(zipFilePath);
             ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(fileInputStream, password)) {

            ArchiveEntry entry;
            while ((entry = zipArchiveInputStream.getNextZipEntry()) != null) {
                if (!zipArchiveInputStream.canReadEntryData(entry)) {
                    continue;
                }

                String entryName = entry.getName();
                File entryFile = new File(destinationFolderPath, entryName);

                if (entry.isDirectory()) {
                    entryFile.mkdirs();
                } else {
                    new File(entryFile.getParent()).mkdirs();

                    try (FileOutputStream outputStream = new FileOutputStream(entryFile)) {
                        int bytesRead;
                        while ((bytesRead = zipArchiveInputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
        }
    }



}
